namespace CSharpPro._1020;

public class Demo5
{
    //1020作业一冒泡排序
    public void TestPrint1(int[] array)
    {
        Console.WriteLine("排序前的数组：");
        PrintArray(array);
        
        BubbleSort(array);
        
        Console.WriteLine("排序后的数组（升序）：");
        PrintArray(array);
    }
    private void BubbleSort(int[] array)
    {
        if (array == null || array.Length <= 1)
            return;
        int length = array.Length;
        for (int i = 0; i < length - 1; i++)
        {
            bool swapped = false;

            for (int j = 0; j < length - 1 - i; j++)
            {
                if (array[j] > array[j + 1])
                {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    swapped = true;
                }
            }

            if (!swapped)
                break;
        }
    }
    private void PrintArray(int[] array)
    {
        if (array == null || array.Length == 0)
        {
            Console.WriteLine("(空数组)");
            return;
        }
        Console.WriteLine(string.Join(" ", array));
    }
}